(function () {

    /* Framework.js */
    function Framework() {
        var photoArray;
        var interval; /* is using in checkNick() */

        this.init = function () {
            if (dom('#rating')) {
                dom('#rating').elements[0].onmouseover = function () {
                    showRatingBar();
                };
                dom('#rating').elements[0].onmouseout = function () {
                    hideRatingBar();
                };
            };
            if((framework.checkLoginStatus() === -1) && dom('.rate-bar')) {
                var rateBar = dom('.rate-bar');
                rateBar.html(''); //clear rate-bar
                rateBar.createElement('div').className = 'login-message';
                dom('.login-message').html('Please login to be able to rate the picture.');
            }
        };
        
        //Templates

        getTemplateNames = function () {
            return dom('A[data-template]').getAttrValue('data-template'); //return the list of templates names
        };

        setTemplate = function (template) { //put template in the required place
            ajax({
                url: 'templates/' + template + '.tmpl',
                parse_json: false,
                success: function (tmpl) {
                    dom('A[data-template=' + template + ']').html(tmpl); //inserting template
                    dom('A[data-template=' + template + ']').removeClass('loader');
                },
                error: function () {
                    console.log('Oops... Something wrong. Template "' + template + '" not loaded.');
                }
            });
        };
        
        setDialog = function (tmpl) { //creating and uploading template content
            var tmplContent = dom('#main-wrapper').createElement('div');
            tmplContent.className = 'tmpl-content';
            tmplContent.setAttribute('data-template', tmpl);
            tmplContent.setAttribute('data-dialog', tmpl);
            tmplContent.className += (" loader");
            setTemplate(tmpl);
        };
        
        this.showDialogForm = function (tmpl) { //hide not required templates and show required
            if (!dom('A[data-dialog]')) {
                var back;
                back = dom('#main-wrapper').createElement('div');
                back.className = 'back';
                setDialog(tmpl);
                back.onclick = function () {
                    dom('.back').addClass('hidden');
                    dom('A[data-dialog]').addClass('hidden');
                };
            } else {
                if (dom('A[data-dialog=' + tmpl + ']')) {
                    dom('A[data-dialog]').addClass('hidden');
                    dom('A[data-dialog=' + tmpl + ']').removeClass('hidden');
                    dom('.back').removeClass('hidden');
                } else {
                    dom('A[data-dialog]').addClass('hidden');
                    dom('.back').removeClass('hidden');
                    setDialog(tmpl);
                }
            }
        };

        this.fillTemplates = function () {
            var templates = getTemplateNames();
            if (templates) {
                for (var i = 0; i < templates.length; i++) {
                    setTemplate(templates[i]);
                };
            }
        };
        
        //End of templates
        
        //Rating

        setRatingBar = function (photoId) { //setting rating-bar
            ajax({
                url: "ajax/checkIfRated.php?photoid=" + photoId,
                parse_json: true,
                success: function (rating) {
                    var rateBar = dom(".rate-bar");
                    var userMark = dom("#user-rating");
                    if (rating.data === "not rated yet") {
                        rateBar.removeClass("disabled");
                        rateBar.addClass("active");
                        userMark.html("Vote");
                        dom('.rate-container').elements[0].onmouseout = function () {
                            clearPrevious();
                        };
                        for (var i = 0; i < dom('.rate-container').elements[0].children.length; i++) {
                            (function (mark) {
                                dom('.rate-container').elements[0].children[i].onmouseover = function () {
                                    fillPrevious(mark);
                                };
                                dom('.rate-container').elements[0].children[i].onclick = function () {
                                    saveRating(photoId, mark);
                                };
                            }(i));
                        };
                    } else {
                        rateBar.removeClass("active");
                        rateBar.addClass("disabled");
                        userMark.html(rating.data);
                        dom('.rate-container').elements[0].onmouseout = function () {};
                        for (var i = 0; i < dom('.rate-container').elements[0].children.length; i++) {
                            (function (i) {
                                dom('.rate-container').elements[0].children[i].onmouseover = function () {};
                                dom('.rate-container').elements[0].children[i].onclick = function () {};
                            }(i));
                        };
                    }
                },
                error: function () {
                    console.log("not possible to get data;");
                }
            });
        }
        
        saveRating = function (photoId, mark) { //saving rating in the data base for photoId
            if (dom('.active-rate-bar')) {
                dom('.active-rate-bar').removeClass('active-rate-bar');
            }
            for (var i = 0; i <= mark; i++) {
                dom('.rate-container').elements[0].children[i].className = 'active-rate-bar';
            }
            var savedMark = mark + 1; //counting starts from zero
            savedMark = savedMark + '.0';
            dom('#user-rating').html(savedMark);
            ajax({
                url: "ajax/setRating.php?photoid=" + photoId + "&rating=" + savedMark,
                parse_json: false,
                success: function (respons) {
                    if (respons.errormessage) {
                        console.log(respons.errormessage);
                    } else {
                        console.log("Server: " + respons.data);
                    }
                },
                error: function () {
                    console.log("Saving rating error.");
                }
            });
        }

        fillPrevious = function (mark) { //filling the previous items
            if (!dom('.hover-rate-bar')) {
                for (var i = 0; i < mark; i++) {
                    dom('.rate-container').elements[0].children[i].className += ' hover-rate-bar';
                }
            }
        }

        clearPrevious = function () { //clearing the previous items
            if (dom('.hover-rate-bar')) {
                dom('.hover-rate-bar').removeClass('hover-rate-bar');
            }
        }

        showRatingBar = function () { //show rating-bar on hover
            var rating = dom('#rating');
            rating.setClass('showed-rating'); //
            if (dom('.rate-bar')) {
                dom('.rate-bar').removeClass('hidden');
                dom('.mark').addClass('hidden');
            }
        }

        hideRatingBar = function () { //hide rating-bar and show average rating
            var rating = dom('#rating');
            rating.setClass('hided-rating'); //
            if (dom('.rate-bar')) {
                dom('.mark').removeClass('hidden');
                dom('.rate-bar').addClass('hidden');
            }
        }
        
        //End of rating
        
        initMap = function (lat,lng) {
            var latlng = new google.maps.LatLng(lat,lng);
            var mapOptions = {
                center: latlng,
                zoom: 10,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(dom("A[data-template=map]").elements[0],
                mapOptions);
            addMarker(latlng, map);
        }
        
        addMarker = function (location, map) {
            marker = new google.maps.Marker({
                position: location,
                map: map
            });
        }
        
        loadMap = function (img) {
            framework.showDialogForm("map");
            initMap(img.latitude,img.longitude);
        }

        /*
         * Load and change the background image on random on load event
         */
        this.loadIndexImage = function () {
            if (dom("A[data-rndbackground]")) {
                var elem = dom("A[data-rndbackground]").elements[0];
                dom('#content').addClass('loader-large');
                dom('#content').removeClass('cover');
                elem.removeAttribute('style');
                ajax({
                    url: './ajax/getBestsPhotos.php?count=5',
                    parse_json: true,
                    success: function (photos) {
                        var photoArray = photos.data;
                        var content = dom("#content").elements[0];
                        for (var i = 0; i < photos.data.length; i++) {
                            var img = document.createElement("img");
                            img.className = "content-bg-img";
                            img.src = "./photos/" + photos.data[i].filename;
                            img.setAttribute("data-complete", "false");
                            img.setAttribute("onload", "this.setAttribute('data-complete', 'true');");
                            content.appendChild(img);

                            if (dom("#change-photo-holder")) {
                                var btn = document.createElement("div");
                                btn.className = "change-photo-btn";
                                dom('#change-photo-holder').elements[0].appendChild(btn);
                            }

                        }
                        if (dom('.change-photo-btn')) {
                            for (var i = dom(".change-photo-btn").elements.length - 1; i >= 0; i--) {
                                dom('.change-photo-btn').elements[i].onclick = function () {
                                    framework.setIndexImage(photoArray, dom('.change-photo-btn').elements.indexOf(this));
                                }
                            }
                        }

                        framework.setIndexImage(photoArray, 0);
                        return slide = setInterval(function () {
                            framework.setIndexImage(photoArray, Math.floor(Math.random() * (dom(".content-bg-img").elements.length - 1)));
                        }, 10000);
                    },
                    error: function () {
                        if (dom("A[data-rndbackground]")) {
                            var elem = dom("A[data-rndbackground]").elements[0];
                            elem.style.backgroundImage = "url('./photos/" + dom("A[data-rndbackground]").getAttrValue('data-rndbackground') + "')";
                        }
                    }
                });
            }

        };

        /* Set background image */

        this.setIndexImage = function (photos, index) {
            if (dom("A[data-rndbackground]")) {
                var elem = dom("A[data-rndbackground]").elements[0];
                var content = dom('#content').elements[0];
                var img = dom(".content-bg-img").elements[index];
                if (img.getAttribute("data-complete") === 'true') {
                    dom('#content').removeClass("loader-large");
                    dom('#content').addClass('cover');
                    elem.style.backgroundImage = "url('" + img.src + "')";

                    if (dom("#photo-description")) {
                        dom("#photo-name").html("<a href='#'>" + photos[index].title + "</a>");
                        dom("#author").html("<a href='view.html#photographer/" + photos[index].user.id + "'>" + photos[index].user.nickname + "</a>");
                        dom("#photo-description-content").html(photos[index].description);
                        dom("#photo-description").removeClass('loader');
                    }

                    if (dom(".change-photo-btn-active")) {
                        dom(".change-photo-btn-active").removeClass("change-photo-btn-active");
                    }

                    if (dom('.change-photo-btn')) {
                        dom('.change-photo-btn').elements[index].className += " change-photo-btn-active";
                    }

                    var rating = parseFloat(photos[index].rating).toFixed(1);
                    if (dom("#avr-rating")) {
                        dom("#avr-rating").html(rating);
                    }
                } else {
                    setTimeout(function () {
                        framework.setIndexImage(photos, Math.floor(Math.random() * (dom(".content-bg-img").elements.length - 1)))
                    }, 500);
                }
            }
        };

        /* Fill data on the photographers page */

        this.fillPhotographersTable = function () {
            ajax({
                url: './ajax/getUserList.php',
                parse_json: true,
                success: function (photographers) {
                    var list = document.createElement("ul");
                    for (var i = 0; i < photographers.data.length; i++) {
                        var item = document.createElement("li");
                        item.innerHTML += "<a href='view.html#photographer/" + photographers.data[i].id + "'>" + photographers.data[i].nickname + "</a>";

                        for (var n = 0; n < photographers.data[i].photos.data.length; n++) {
                            item.innerHTML += '<span>' + photographers.data[i].photos.data[n].title + '(' + photographers.data[i].photos.data[n].count + ') ' + '</span>';
                        }
                        list.appendChild(item);
                    }
                    if (dom("#ph_list")) {
                        var content = dom('#ph_list').elements[0];
                        content.appendChild(list);
                    }
                },
                error: function () {

                }
            });
        }

        /* Upload page functions */

        /* Action of choose photo button on upload page*/ 

        this.startupload = function () {
            if (framework.checkLoginStatus() != -1) {
                dom('#uploadprogress').removeClass('hidden');
                dom('#fileuploader').addClass('hidden');
                framework.handleSubmit(document.getElementById('uploadform'));
            } else {
                alert("Log in to upload files.");
            }
        }

        /* Upload user image and show inputs on upload page */

        this.handleSubmit = function (f) {
            var inpt = f.elements["file"];
            var file;
            if (inpt.files == null || inpt.files == undefined || !inpt.files) {
                var arr = inpt.value.split("\\");
                file = arr[arr.length - 1];
            } else {
                file = inpt.files[0];
            }
            var formData = new FormData();
            formData.append("file", file);
            ajax({
                url: './ajax/upload.php',
                method: 'POST',
                data: formData,
                async: true,
                parse_json: true,
                contentType: false,
                success: function (data) {
                    if (data.data == "") {
                        dom('#fileuploader').removeClass('hidden');
                        dom('#uploadprogress').addClass('hidden')
                        alert("Wrong image size. Try again.");
                    } else {
                        framework.fillUploadFormData();
                        dom('#uploadprogress').addClass('hidden');
                        dom('#uploadresult').removeClass('errorMessage');
                        dom('#uploadresult').removeClass('hidden');
                        dom('#fieldsuploader').removeClass('hidden');
                        dom('#uploadresult').html('<img src="./photos/' + data.data.filename + '"/><br><p><input type="button" onclick="framework.reload();" id="reload-btn" class="default-button" value="Upload another photo"/></p>');
                        google.maps.event.addDomListener(window, 'load', framework.initUploadMap()); // Julia
                        var fileName = dom("#fileName").elements[0];
                        fileName.value = data.data.filename;
                        tagsInit(); // [zgoral] - initialize tags feature
                    }
                },
                error: function () {
                    dom('#uploadprogress').addClass('hidden');
                    dom('#uploadresult').removeClass('hidden');
                    dom('#uploadresult').addClass('errorMessage');
                    dom('#uploadresult').html('error');
                }
            });
        }

        /* Fill inputs on the upload page */

        this.fillUploadFormData = function () {
            ajax({
                url: './ajax/getCategoryList.php',
                parse_json: true,
                success: function (categories) {
                    var html = "";
                    for (var i = 0; i < dom('#uploadCategory').elements[0].options.length; i++) {
                        dom('#uploadCategory').elements[0].remove(i);
                    }
                    for (var i = 0; i < categories.data.length; i++) {
                        html += "<option value='" + categories.data[i].id + "'>" + categories.data[i].title + "</option>";
                    }
                    dom("#uploadCategory").html(html);
                    var date = new Date();
                    var day = date.getDate();
                    var month = date.getMonth() + 1;
                    var year = date.getFullYear();
                    if (month < 10) month = "0" + month;
                    if (day < 10) day = "0" + day;
                    var today = year + "-" + month + "-" + day;
                    document.forms['uploadDescriptionForm'].elements['uploadDate'].setAttribute("value", today);
                },
                error: function () {
                    dom("#uploadCategory").html("Error in load categories");
                }
            });
        }

        /* Reload image on upload page */

        this.reload = function () {
            dom('#uploadprogress').addClass('hidden');
            dom('#uploadresult').addClass('hidden');
            dom("#fieldsuploader").addClass('hidden');
            dom('#fileuploader').removeClass('hidden');
            var uplFile = document.forms["uploadform"].elements["file"];
            uplFile.addEventListener('change', startupload, false);
        }

        /* Send data from upload page */

        this.sendData = function (form) {
            var userId = framework.checkLoginStatus();
            var title = form.elements["uploadTitle"].value;
            var categoryId = form.elements["uploadCategory"].options[form.elements["uploadCategory"].selectedIndex].value;
            var description = form.elements["uploadDescrText"].value;
            var filename = dom("#fileName").elements[0].value;
            var tags = form.elements["tags"].value;
            var date = form.elements["uploadDate"].value;
            var latitude = form.elements["latitude"].value;
            var longitude = form.elements["longitude"].value;
            var formData = new FormData();
            formData.append("user_id", userId);
            formData.append("title", title);
            formData.append("categoryid", categoryId);
            formData.append("description", description);
            formData.append("filename", filename);
            formData.append("tags", tags);
            formData.append("date", date);
            formData.append("latitude", latitude);
            formData.append("longitude", longitude);
            var result = false;
            if(checkForm('upload')){
                ajax({
                    url: './ajax/send.php',
                    method: 'POST',
                    data: formData,
                    async: true,
                    parse_json: true,
                    contentType: false,
                    success: function (title) {
                        if (title.data.uploaded == true) {
                            alert("Upload photo successfull!");
                            window.location = "view.html#photographer/" + userId;
                        }
                        result = true;
                    },
                    error: function () {
                        result = false;
                    }
                });
            }
            return result;
        }

        /* End of upload page functions */
        
        this.registration = function () {
            var userName = dom('#user-name-reg').elements[0].value;
            var userPassword = dom('#user-password-reg').elements[0].value;
            var userNick = dom('#user-nick-reg').elements[0].value;
            var result = false;
            if (checkForm('reg') && this.confirmPass()) {
                ajax({ url: 'ajax/register.php?email=' + userName + '&password=' + userPassword + '&nickname=' + userNick,
                    parse_json: true, 
                    async: false, 
                    success: function(user) { 
                        if (user.data.logged == true) {
                            alert('Registration successfull');
                            setTimeout(function() {location.reload()}, 1000);
                            result = true;
                        }
                        else {
                            dom("#register-error").removeClass('hidden');
                            dom("#register-error").html(user.errormessage);
                            result = false;
                        }
                    }, 

                    error: function() {
                        result = false;
                    }
                });
                return result;
            }
            else {
                return false;
            }
        }

        this.checkNick = function () {
            var userNick = dom('#user-nick-reg').elements[0].value;
            var result = false;

            clearTimeout(interval);
            interval = setTimeout(function(){
                if (userNick.length > 2) {
                    ajax({
                        url: 'ajax/checkUserNickname.php?nickname=' + userNick,
                        parse_json: true,
                        async: false,
                        success: function(user) {
                            if (user.data.length > 0) {
                                dom("#nick-error").html('This nickname is already taken');
                                dom("#user-nick-reg").addClass('error');
                                result = false;
                            }
                            else {
                                dom("#nick-error").html('');
                                dom("#user-nick-reg").removeClass('error');
                                result = true;
                            }
                        },
                        error: function() {
                            return false;
                        }
                    });
                }
                return result;
            },2000);
        }

        this.confirmPass = function () {
            var pass1 = dom('#user-password-reg').elements[0].value;
            var pass2 = dom('#user-pass-confirm-reg').elements[0].value;
                    if (pass1 != pass2) {
                dom("#pass-confirm-error").html('Passwords must coincide');
                dom("#user-pass-confirm-reg").addClass('error');
                return false;
            }
            else {
                dom("#pass-confirm-error").html('');
                dom("#user-pass-confirm-reg").removeClass('error');
                return true;
            }
        }

        this.login = function () {
            var userName = dom('#user-name').elements[0].value;
            var userPassword = dom('#user-password').elements[0].value;
            var result = false;
            if (checkForm('login')) {
                ajax({
                    url: 'ajax/login.php?email=' + userName + '&password=' + userPassword,
                    parse_json: true,
                    async: false,
                    success: function (user) {
                        if (user.data.logged == true) {
                            dom("#login-error").addClass('hidden');
                            result = true;
                        } else {
                            dom("#login-error").removeClass('hidden');
                            result = false;
                        }
                    },

                    error: function () {
                        result = false;
                    }
                });
                return result;
            } else {
                return false;
            }
        }

        /* Logout from website */

        this.logout = function () {
            ajax({
                url: './ajax/logout.php',
                parse_json: false,
                async: false,
                success: function () {
                    dom('#menu-login').removeClass('hidden');
                    dom('#menu-upload').addClass('hidden');
                    dom('#menu-nickname').addClass('hidden');
                    dom('#menu-logout').addClass('hidden');
                    window.location.assign("index.html");
                },
                error: function () {
                    console.log('failed to logout');
                }
            });
        };
        
        /* Check if user is logged in */

        this.checkLoginStatus = function () {
            var id = -1;
            ajax({
                url: './ajax/scheck.php',
                parse_json: true,
                async: false,
                success: function (status) {
                    if (status.data.logged === "true") {
                        id = status.data.user_id;
                    }
                },
                error: function () {
                    console.log('login status check error');
                }
            });
            return id;
        };

        /* Load submenu in header */

        this.loadSubMenu = function () {
            ajax({
                url: './ajax/getCategoryList.php',
                parse_json: true,
                success: function (categories) {
                    var html = "";
                    for (var i = 0; i < categories.data.length; i++) {
                        var anch = document.createElement("a");
                        var txt = document.createTextNode("" + categories.data[i].title + "");
                        anch.href = "view.html#category/" + categories.data[i].id + "";
                        anch.appendChild(txt);
                        html += "<li>" + anch.outerHTML + "</li>";
                    }
                    if (dom("#sub-menu")) {
                        dom("#sub-menu").html(html);
                    }
                },
                error: function () {
                    console.log('failed to load sub menu categories');
                }
            });
        };

        /* Set user menu after login */

        this.setUserMenu = function () {
            var userId = this.checkLoginStatus();
            if (userId != -1) {
                ajax({
                    url: './ajax/getUserList.php?userid=' + userId,
                    parse_json: true,
                    success: function (photographer) {
                        var username = photographer.data[0].nickname;
                        var html = "";
                        html += "<a>" + username + "</a>";
                        dom('#menu-nickname').html(html);
                        dom('#menu-login').addClass('hidden');
                        dom('#menu-upload').removeClass('hidden');
                        dom('#menu-nickname').removeClass('hidden');
                        dom('#menu-logout').removeClass('hidden');
                    },
                    error: function () {}
                });
            }
        };

        /* Display image in full screen */

        this.showImageFullScreen = function (imgURL) {
            if (dom(".lightbox") === false) {
                var shadow = document.createElement("div");
                var lightboxContent = document.createElement("div");
                var content = dom("#main-wrapper").elements[0];

                shadow.className = "lightbox";
                lightboxContent.className = "lightbox-content";
                lightboxContent.style.backgroundImage = "url('" + imgURL + "')";
                shadow.appendChild(lightboxContent);
                content.appendChild(shadow);

                dom(".lightbox").elements[0].onclick = function () {
                    dom(".lightbox").addClass("hidden");
                };

            } else {
                var lightboxContent = dom(".lightbox-content").elements[0];
                lightboxContent.style.backgroundImage = "url('" + imgURL + "')";
                dom(".lightbox").removeClass("hidden");
            }
        };
        
        /* Search function */

        this.searchItem = function () {
            var searchItem = dom('#search-field').elements[0].value;
            window.location = "view.html#search/" + searchItem;
            return false;
        };
        
        /* Initialize a map on upload page */
        
        this.initUploadMap = function () {
            var mapOptions = {
                center: new google.maps.LatLng(50.5, 30.466667),
                zoom: 5
            };
            var map = new google.maps.Map(document.getElementById('map'), mapOptions);
            google.maps.event.trigger(map, 'resize');
            var input = document.getElementById('place');
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
            var autocomplete = new google.maps.places.Autocomplete(input);
            autocomplete.bindTo('bounds', map);
            var marker = new google.maps.Marker({
                map: map
            });

            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                marker.setVisible(false);
                var place = autocomplete.getPlace();
        
                if (!place.geometry) {
                    return;
                }
                if (place.geometry.viewport) {
                    map.fitBounds(place.geometry.viewport);
                } else {
                    map.setCenter(place.geometry.location);
                    map.setZoom(10);
                }
        
                marker.setIcon({
                    url: './styles/images/camera.png',
                    size: new google.maps.Size(70, 70),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 30),
                    scaledSize: new google.maps.Size(35, 35)
                });
        
                marker.setPosition(place.geometry.location);
                marker.setVisible(true);
        
                dom('#latitude').elements[0].value = place.geometry.location.lat();
                dom('#longitude').elements[0].value = place.geometry.location.lng();
            });
        
        };
        
    };
    

    /* end of Framework.js */

    if (!window.framework) window.framework = new Framework();

    window.onload = function () {
        window.framework.init();
        window.framework.fillTemplates();
        window.framework.loadIndexImage();
        window.framework.loadSubMenu();
        window.framework.setUserMenu();
        if(dom("#ph_list")){
            window.framework.fillPhotographersTable();
        }

        document.createElement('header'); //ie8 html5 fix
        document.createElement('nav');
        document.createElement('menu');
        document.createElement('section');
        document.createElement('article');
        document.createElement('aside');
        document.createElement('footer');
    };

})();